package com.htc.callcare.activities;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.concurrent.ExecutionException;
import com.htc.callcare.R;
import com.htc.callcare.adapter.RecordAdapter;
import com.htc.callcare.asyntask.AsynLoadAllRecordFile;
import com.htc.callcare.database.Database;
import com.htc.callcare.infrastructure.globalVar;
import com.htc.callcare.model.recordModel;
import com.htc.callcare.viewcontroller.Player;
import com.htc.callcare.viewcontroller.RecordController;
import com.htc.callcare.viewcontroller.Record_Detail_View;
import com.htc.callcare.viewcontroller.Record_Note_View;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class RecordActivity extends Activity {
	ListView lviewRecord;
	RecordAdapter adapter;
	Player player;
	LinearLayout  playLayout;
	ArrayList<recordModel> records;
	Hashtable hashtable = new Hashtable();
	boolean playerIsShown =false;
	RelativeLayout parent;
	RecordController recordController;
	recordModel processModel;
	Record_Detail_View detail;
	Record_Note_View note;
	ArrayList<View> allAttachView = new ArrayList<View>();
	String contact_name;
	Database database;
	TextView noRecordFile;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.record_screen);
		initView();
	}

	private void initView() {
		database = new Database(this);
		lviewRecord = (ListView) findViewById(R.id.listRecord);
		player = new Player(RecordActivity.this);
		//init a record controller
		recordController = new RecordController(this);
		parent = (RelativeLayout) findViewById(R.id.record_parent_View);
		playLayout = (LinearLayout) findViewById(R.id.layoutPlay);
		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		playLayout.addView(player, params);
		player.hidePlayer();
		///Init Record detail
		detail = new Record_Detail_View(this);
		parent.addView(detail);
		detail.setVisibility(View.GONE);
		allAttachView.add(detail);
		//Init Note
		note = new Record_Note_View(this);
		parent.addView(note);
		note.setVisibility(View.GONE);
		allAttachView.add(note);
		//SHOW if no record file
		noRecordFile = (TextView) findViewById(R.id.noRecordFile);
	}

	public void onResume() {
		super.onResume();
		updateAdapter();
		registerForContextMenu(lviewRecord);
		
	}

	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.record_context_menu, menu);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		if(records.size()!=0){
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);}
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.delete:
			Toast.makeText(getApplicationContext(), "delete", Toast.LENGTH_SHORT).show();
			//Get view Item
			int count = lviewRecord.getCount();
			
			Log.e("thuutai", ""+(count==records.size()? "equal":"not equal")+" listView "+count+" records: "+records.size());
			int recordSize = records.size();
			for(int i = 0;i<recordSize;i++){			
				if(records.get(i).getSeparator()==0){
					if(database.getCheckItem(records.get(i).getFileUri())){
						Log.v("thuutai", "delete file uri"+records.get(i).getFileUri());
						recordController.deleteItem(records.get(i));
						database.deleteCheckItem(records.get(i).getFileUri());
					}
				}
					
			}
			this.finish();
			startActivity(new Intent(this, RecordActivity.class));
			break;

		default:
			break;
		}
		return true;
	}

	public Hashtable getAllContactName() {

		Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		String[] projection = new String[] {
				ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.NUMBER };

		Cursor people = getContentResolver().query(uri, projection, null, null,
				null);

		int indexName = people
				.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
		int indexNumber = people
				.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

		people.moveToFirst();
		do {
			String name = people.getString(indexName);
			String number = people.getString(indexNumber);
			hashtable.put(number, name);
			// Do work...
		} while (people.moveToNext());
		return hashtable;
	}

	public void setRecordFile(String fileUri) {
		hideAllView();
		if(records.size()>0){
		player.setFilename(fileUri);
		player.setPlayer();
		Toast.makeText(getApplicationContext(), "Play", Toast.LENGTH_SHORT).show();
		}
	}
	
	protected void onDestroy() {
        // TODO Auto-generated method stub
		player.release();
        super.onDestroy();
    }
	
	protected void onPause() {
        // TODO Auto-generated method stub
		player.stop();
        super.onPause();
    }
	
	public void showPlayerView(){
		player.setVisibility(View.VISIBLE);
	}
	
	public boolean hasVisibleView() {
		for (View subView : allAttachView) {
			if (subView.getVisibility() == View.VISIBLE) {
				return true;
			}
		}
		return false;
	}
	
	@Override
	public void onBackPressed() {
		if(hasVisibleView()){
			hideAllView();
		}
		else{
			super.onBackPressed();
		}
	}

	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.call:
			Intent callIntent = new Intent(Intent.ACTION_CALL);
			callIntent.setData(Uri.parse("tel:"+processModel.getCallNumber()));
			startActivity(callIntent);
			return true;
		case R.id.view_note:
			note.setVisibility(View.VISIBLE);
			note.setProcessModel(processModel, RecordActivity.this);
			return true;
		case R.id.share:
			recordController.send(processModel);
			return true;
		case R.id.view_detail:
			detail.setVisibility(View.VISIBLE);
			detail.setProcessModel(processModel, contact_name);
			return true;
		case R.id.delete:
			recordController.detete(processModel, adapter);
			return true;

		default:
			return super.onContextItemSelected(item);
		}
	}

	public void setItemSelect(recordModel model, String contact_name) {
		this.processModel = model;
		this.contact_name = contact_name;
	}
	
	
	public void updateAdapter(){
		AsynLoadAllRecordFile loadAllRecordFile = new AsynLoadAllRecordFile(
				this, "Loading");
		loadAllRecordFile.execute();
		try {
			records = loadAllRecordFile.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(records.size()!=0){
			adapter = new RecordAdapter(this, records, getAllContactName());
			lviewRecord.setAdapter(adapter);
			
		}
		else{
			noRecordFile.setVisibility(View.VISIBLE);
		}
		
		
	}
	
	public void hideAllView() {
		for (View subView : allAttachView) {
			if (subView.getVisibility() == View.VISIBLE) {
				subView.setVisibility(View.GONE);
			}
		}

	}
}
	
